package com.qf.ks.service.impl;

import com.qf.ks.constans.ResultCode;
import com.qf.ks.mapper.UserMapper;
import com.qf.ks.dto.UserDto;
import com.qf.ks.exception.AddDataException;
import com.qf.ks.pojo.Users;
import com.qf.ks.pojo.Yan;
import com.qf.ks.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class UsersServiceImpl implements UsersService {

    private UserMapper userMapper;
    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public void AddUsers(UserDto user) {
        List<String> usernameList = userMapper.usernameList();
        System.out.println("4154");
        for (String name:usernameList) {
            if (user.getUsername().equals(name)){
                throw new AddDataException("用户名存在", ResultCode.USERNAME_EXIST);
            }
        }
        if (user==null){
            throw new AddDataException("世界毁灭了", ResultCode.NULL_DATA);
        }else if (user.getUsername()==null){
            throw new AddDataException("用户名为空世界没毁灭", ResultCode.NULL_NAME);
        }else if (user.getPassword()==null){
            throw new AddDataException("密码为空", ResultCode.NULL_PASSWORD);
        }else if (!user.getPassword().equals(user.getRepeatPassword())){
//            System.out.println(user.getPassword()+user.getRepeatPassword());
            throw new AddDataException("两次密码不一致", ResultCode.PASSWORD_INCONSISTENCY);
        }
        Users users=new Users();
        users.setUsername(user.getUsername());
        Yan yan=new Yan();
        String data = yan.getData();
        System.out.println(data);
        users.setPasswordsalt(data);
        String password=data+user.getPassword();
        users.setPassword(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)));
        users.setRegistrydate(new Date());
        users.setLastlogindate(new Date());
        users.setCurrentlogindate(new Date());
        userMapper.addUser(users);

    }
}
